package demo.java.future;

import org.junit.Test;
import org.mockito.Mock;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.Async;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author wangly on @date 2023/5/22
 */
public class FutureTest {
    @Mock
    AsyncTaskExecutor asyncTaskExecutor;
    @Test
    public void runTest() {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);

        List<CompletableFuture<String>> futures = new ArrayList<>();

        // 提交多个任务
        for (int i = 0; i < 5; i++) {
            int taskId = i;
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> performTask(taskId), executor);
            futures.add(future);
        }

        // 等待所有任务完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));

        try {
            // 等待所有任务完成
            allFutures.get();

            // 获取每个任务的结果
            for (CompletableFuture<String> future : futures) {
                String result = future.get();
                System.out.println("Task result: " + result);
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        // 关闭线程池
        executor.shutdown();
    }

    public String performTask(int taskId) {
        System.out.println("start "+taskId);
        // 模拟一个耗时的任务
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(taskId == 2){
            try {
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("end "+taskId);
        return "Task " + taskId + " completed";
    }
}